<html>
<head>
<script type="text/javascript">
	
	// submit the form when its finished loading
	function submitForm()
	{
		var elements = document.getElementsByTagName("form")
		
		if(elements.length > 0)
		{
			elements[0].submit();	
		}
	}

</script>
</head>
<body onload="submitForm()">
	<?php
    # Logging in with Google accounts requires setting special identity, so this example shows how to do it.
    
    require 'openid.php';
    require '..\DAL\ConnectionManager.php';
    require '..\DAL\DBIO.php';
    require '..\Environment\EnvManager.php';
    require '..\Security\Token.php';
    
    if(ENV_TYPE == EnvTypes::DEV)
    {
        
        // we'r in dev here so we can simply run in dev mode
        DoLogin(DEV_EMAIL, DEV_ID);
        
    }else
    {
        
        // We'r in the live here so we need to do actually authenticate against google
        try {
            $openid = new LightOpenID;
            if(!$openid->mode) {
                if(isset($_GET['login'])) {
                    $openid->identity = 'https://www.google.com/accounts/o8/id';
                    $openid->required = array('namePerson/friendly', 'contact/email');
                    header('Location: ' . $openid->authUrl());
                }
        ?>
        <form action="?login" method="post">
            <noscript>
            You need javascipt enabled to login automatically.
            <button>Login with Google</button>
        	</noscript>
            Logging in ...
        </form>
        <?php
            } elseif($openid->mode == 'cancel') {
                // TODO: Send the user back to the main page
                echo 'User has canceled authentication!';
            } else {
                            
                $openid->validate();
                
                // do the login 
                DoLogin($openid->data["openid_ext1_value_contact_email"], $openid->identity);
                    
                
            }
        } catch(ErrorException $e) {
            echo $e->getMessage();
        }
    }
	
	/*
	** perform the login logic
	*/
	function DoLogin($email, $identity)
	{
		// now that the user has been authenticated we need to check if they are in the database
	
		$DBObj = new DBIO();
		
		// see if the user is in the database
		if(!$DBObj->IsUserInDB($email))
		{
			// the user is not in the database so add them
			$DBObj->AddUserToDB($email, $identity);	
		}
			
		// generate the users token
		$SecObj = new Token();
		
		$tok = $SecObj->GenerateToken(); 
		
		// store token in DB
		$DBObj->AddTokenToDB($email, $tok);
		
		// send them to the silverlight lab login page with their token
		header('Location:' . LAB_URL . "?token=" . $tok . "&" . "email=" . $email);
		
		
	}
	?>
</body>
</html>